package my.diplom.dao.impl;

import java.util.List;


import org.springframework.orm.hibernate3.HibernateTemplate;
import org.apache.log4j.Logger;
import my.diplom.dao.IUserDAO;
import my.diplom.entity.User;
import my.diplom.entity.Resource;
import my.diplom.exceptions.UserNotFoundException;

public class UserDAOImpl implements IUserDAO {


    private static final Logger log = Logger.getLogger(UserDAOImpl.class);

    private HibernateTemplate template;

    public void setTemplate(HibernateTemplate template) {
        this.template = template;
    }

    public void create(User user) {
        log.debug("create user " + user.getFirstName() + " " + user.getLastName());
        template.save(user);
        template.flush();

    }

    public void delete(User user) {
        log.debug("delete user = " + user.getFirstName() + " " + user.getLastName());
        template.delete(user);

    }

    public List<User> getAll() {
        log.debug("get all users");
        //noinspection JpaQlInspection
        return template.find("FROM User order by login");
    }

    public List<User> getAll(boolean initProjects) {
        List<User> users = template.find("FROM User order by login");
        for (User u : users) {
            template.initialize(u.getProjects());
        }
        return users;
    }

    public User getById(Long userId) {
        log.debug("get user by id = " + userId);
        return (User) template.get(User.class, userId);
    }

    public void update(User user) {
        log.debug("update user = " + user.getFirstName() + " " + user.getLastName());
        template.saveOrUpdate(user);

    }

    public User getByLogin(String login) throws UserNotFoundException {
        log.debug("get user by login = " + login);
        try {
            //noinspection JpaQlInspection
            return (User) template.find("from User u where u.login = ?", login).get(0);
        } catch (IndexOutOfBoundsException e) {
            log.error("user " + login + " does not exist", e);
            throw new UserNotFoundException("user" + login + " doesnt exist");
        }

    }

    @Override
    public List<User> getUsersByResource(Resource resource) {
        return template.find("select distinct u from User as u join u.projects as p join p.resources as r where r.resourceId = ?", resource.getResourceId());
    }

    @Override
    public User getById(Long userId, boolean initProjects) {
        User u = (User) template.get(User.class, userId);
        if (initProjects) {
            template.initialize(u.getProjects());
        }
        return u;
    }
}
